/*
 * Copyright (c) 2012 Google Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
 * in compliance with the License. You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software distributed under the License
 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
 * or implied. See the License for the specific language governing permissions and limitations under
 * the License.
 */

package hyo.hun.lifemanager.connect;


import java.io.IOException;
import java.util.ArrayList;

import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;

import com.google.api.services.calendar.model.CalendarList;
import com.google.api.services.calendar.model.CalendarListEntry;

/**
 * Asynchronously load the calendars with a progress dialog.
 *
 * @author Ravi Mistry
 */
class AsyncLoadCalendars extends AsyncTask<Void, Void, Void> {

  private final CalendarConnect calendarConnect;
  private Context context;
  private com.google.api.services.calendar.Calendar client;
  private final ProgressDialog dialog;

  AsyncLoadCalendars(CalendarConnect calendarConnect, Context context) {
    this.calendarConnect = calendarConnect;
    this.context = context;
    this.client = CalendarConnect.getClient();
    dialog = new ProgressDialog(context);
  }

  @Override
  protected void onPreExecute() 
  {
	  dialog.setMessage("Loading calendars...");
	  dialog.show();
  }

  @Override
  protected Void doInBackground(Void... arg0) 
  {
	  try 
	  {
    	//calendarConnect.calendars.clear();
    	com.google.api.services.calendar.Calendar.CalendarList.List list = client.calendarList().list();
    	list.setFields("items");
    	CalendarList feed = list.execute();
      
    	if (feed.getItems() != null) 
    	{
    		ArrayList<CalendarInfo> listCalendars = new ArrayList<CalendarInfo>();
    		for (CalendarListEntry calendar : feed.getItems()) 
    		{
    			CalendarInfo info = new CalendarInfo(calendar.getId(), calendar.getSummary());
    			listCalendars.add(info);
    		}
    		calendarConnect.setCalendarList(listCalendars);
    	}
    } catch (IOException e) {
    	e.printStackTrace();
    	//calendarConnect.handleGoogleException(e);
    } finally {
    	//calendarConnect.onRequestCompleted();
    }
    return null;
  }

  @Override
  protected void onPostExecute(Void result) {
	  dialog.dismiss();
  }
}
